'use client';

import React, { useState, useEffect } from 'react';
import { Toaster } from 'react-hot-toast';
import TradingHeader from './components/TradingHeader';
import OrderBook from './components/OrderBook';
import TradingViewChart from './components/TradingViewChart';
import TradingForm from './components/TradingForm';
import OrderManagement from './components/OrderManagement';
import { TokenPair } from './utils/helpers';
import { useMarketData } from './hooks/useMarketData';

export default function TradingPage() {
  const [currentPair, setCurrentPair] = useState<TokenPair>({
    symbol: 'BTC/USDT',
    name: 'Bitcoin',
    price: 0,
    change24h: 0,
    volume24h: 0,
  });

  const [selectedPrice, setSelectedPrice] = useState<number | undefined>();

  // 获取当前交易对的实时数据
  const { tickerStats, loading } = useMarketData({
    symbol: currentPair.symbol.replace('/', ''),  // BTC/USDT -> BTCUSDT
    dataSource: 'binance',
    enableRealtime: true
  });

  // 当获取到真实数据时更新currentPair
  useEffect(() => {
    if (tickerStats) {
      setCurrentPair(prev => ({
        ...prev,
        price: parseFloat(tickerStats.lastPrice),
        change24h: parseFloat(tickerStats.priceChangePercent),
        volume24h: parseFloat(tickerStats.quoteVolume),
      }));
    }
  }, [tickerStats]);

  // 处理从订单簿点击价格
  const handlePriceClick = (price: number) => {
    setSelectedPrice(price);
  };

  // 处理交易对切换
  const handlePairChange = (pair: TokenPair) => {
    setCurrentPair(pair);
    setSelectedPrice(undefined);
  };

  // 格式化价格显示
  const formatPrice = (price: number) => {
    if (loading || price === 0) return 'Loading...';
    return price.toLocaleString(undefined, { 
      minimumFractionDigits: 2, 
      maximumFractionDigits: 2 
    });
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-[#1E2026]">
      <Toaster 
        position="top-right"
        toastOptions={{
          duration: 3000,
          style: {
            background: '#363636',
            color: '#fff',
          },
        }}
      />
      
      {/* 顶部导航栏 */}
      <TradingHeader 
        currentPair={currentPair}
        onPairChange={handlePairChange}
      />

      <div className="container mx-auto px-4 py-6 max-w-[1600px]">
        {/* 主要交易区域 - 调整布局让K线图更大 */}
        <div className="grid grid-cols-12 gap-6 mb-6">
          {/* 左侧：订单簿 - 缩小 */}
          <div className="col-span-12 lg:col-span-2 h-full">
            <OrderBook 
              symbol={currentPair.symbol}
              onPriceClick={handlePriceClick} 
            />
          </div>

          {/* 中部：K线图 - 扩大 */}
          <div className="col-span-12 lg:col-span-8 h-full">
            <TradingViewChart symbol={currentPair.symbol} />
          </div>

          {/* 右侧：交易表单 - 保持 */}
          <div className="col-span-12 lg:col-span-2 h-full">
            <TradingForm 
              currentPrice={currentPair.price}
              symbol={currentPair.symbol}
              onPriceFromOrderBook={selectedPrice}
            />
          </div>
        </div>

        {/* 底部：订单管理 */}
        <div className="mb-6">
          <OrderManagement currentSymbol={currentPair.symbol} />
        </div>
      </div>
    </div>
  );
}
